#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include "Log.hpp"
#include "Common.h"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include <cerrno>
#include <unistd.h>
using namespace LogModule;
static const uint16_t gport = 8080;

#define BACKLOG 8
class TcpServer
{
public:
    TcpServer(int port = gport) : _port(port), _isrunning(false)
    {
    }
    void InitServer()
    {
        // 1.创建TCP  socket
        _listensockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            Die(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket create success, sockfd is : " << _listensockfd;
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = ::htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;
        // 2.绑定
        int n = ::bind(_listensockfd, CONV(&local), sizeof(local));
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            Die(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success, sockfd is : " << _listensockfd;
        // 3.cs,tcp是面向连接的，客户端就要求服务器随时随地等待被连接
        // tcp 需要将socket设置为监听状态
        n = ::listen(_listensockfd, BACKLOG); // 这里不会阻塞，只是改变了一个状态
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "listen error";
            Die(LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen success, sockfd is : " << _listensockfd;
    }
    void HandlerRequest(int sockfd)//TCP也是全双工通信的
    {
        char buffer[4096];
        while (true)
        {
            ssize_t n = ::read(sockfd, buffer, sizeof(buffer) - 1);//从文件描述符里读
            if(n > 0)
            {
                buffer[n] = 0;
                std::string echo_str = "server echo# ";
                echo_str += buffer;

                ::write(sockfd,echo_str.c_str(),echo_str.size());//往文件描述符里写
            }
        }
    }
    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // tcp服务器刚开始不能直接读数据
            // 1.获取新连接
            struct sockaddr_in peer;
            socklen_t peerlen;
            int sockfd = ::accept(_listensockfd, CONV(&peer), &peerlen);
            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error: " << strerror(errno);
                continue;
            }
            // 获取连接成功
            LOG(LogLevel::INFO) << "accept success, sockfd is : " << sockfd;

            // version --0
            HandlerRequest(sockfd);
        }
    }
    void Stop()
    {
        _isrunning = false;
    }
    ~TcpServer()
    {
    }

private:
    int _listensockfd; // 监听套接字
    uint16_t _port;
    bool _isrunning;
};